const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

const User = sequelize.define('User', {
  id: { type: DataTypes.INTEGER.UNSIGNED, primaryKey: true, autoIncrement: true },
  nickName: { type: DataTypes.STRING(50), allowNull: false, field: 'nick_name' },
  avatarUrl: { type: DataTypes.STRING(255), allowNull: true, field: 'avatar_url' },
  openid: { type: DataTypes.STRING(128), allowNull: true, unique: true, field: 'openid' },
  active: { type: DataTypes.TINYINT, allowNull: false, defaultValue: 1, field: 'is_active' },
  // 添加新字段
  gender: { 
    type: DataTypes.ENUM('0', '1', '2'),
    allowNull: true, 
    field: 'gender',
    comment: '性别：0-男，1-女，2-其他'
  },
  city: { 
    type: DataTypes.STRING(100), 
    allowNull: true, 
    field: 'city',
    comment: '城市'
  },
  province: { 
    type: DataTypes.STRING(100), 
    allowNull: true, 
    field: 'province',
    comment: '省份'
  },
  country: { 
    type: DataTypes.STRING(100), 
    allowNull: true, 
    field: 'country',
    comment: '国家'
  }
}, {
  tableName: 'users',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at'
});

// 添加实例方法以确保字段正确序列化
User.prototype.toJSON = function() {
  const values = Object.assign({}, this.get());
  // 确保gender字段正确返回
  if (values.gender !== undefined && values.gender !== null) {
    values.gender = String(values.gender);
  }
  // 移除时间字段
  delete values.created_at;
  delete values.updated_at;
  return values;
};

module.exports = User;